import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author zyj
 * @date 2022年06月09日 11:06
 * Object中的wait(),notify(),notifyAll()来实现
 * wait和 notify必须配合synchronized使用，
 * wait方法释放锁，notify方法不释放锁
 */
public class 线程通信方式三 {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(1);
        List<String> list = new ArrayList<>();
        new Thread(() -> {
            while (true) {
                System.out.println(Thread.currentThread().getName());
                if (list.size() != 5) {
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("线程B执行任务......");
                System.out.println("*******" + latch.getCount());
                break;
            }
        }).start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                list.add("abc");
                System.out.println("线程A向list中添加一个元素，此时list中的元素个数为：" + list.size());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (list.size() == 5) {
                    latch.countDown();
                }
            }
        }).start();



    }
}
